﻿/**************************************************************
 *
 * 唯一标识：f8d8e34c-cfaf-4a77-b87f-fc2246cf7bb2
 * 命名空间：Xunit.Sgr
 * 创建时间：2024/7/21 14:00:24
 * 机器名称：DESKTOP-HJ4OAG9
 * 创建者：CocoYuan
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：
 *
 **************************************************************/

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Sgr;
using Sgr.Data;
using Sgr.Domain.Uow;
using Sgr.EntityFrameworkCore;

namespace Xunit.Sgr.Cap.HelperClass
{
    public static class Extensions
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IServiceCollection AddDbContexts(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddSgrEntityFrameworkCore();

            string dbType = configuration.GetRequiredString("Sgr:DataConnectionStrings:DatabaseType").ToUpper();

            ILoggerFactory myLoggerFactory = LoggerFactory.Create(builder => builder.AddDebug());

            if (dbType == "SQLITE")
            {
                services.UseSqlite(Constant.DEFAULT_DATABASE_SOURCE_NAME, (builder) =>
                {
                    builder
                        .MinBatchSize(1)
                        .MaxBatchSize(1000);

                    //sqlOptions.CharSet(CharSet.Utf8);
                    //sqlOptions.MigrationsAssembly(typeof(Program).Assembly.FullName);
                    //// Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
                    //sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
                }, myLoggerFactory);
            }
            else
            {
                services.UseMySql(Constant.DEFAULT_DATABASE_SOURCE_NAME, (builder) =>
                {
                    builder
                        .MinBatchSize(1)
                        .MaxBatchSize(1000);

                    //sqlOptions.CharSet(CharSet.Utf8);
                    //sqlOptions.MigrationsAssembly(typeof(Program).Assembly.FullName);
                    //// Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
                    //sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
                }, myLoggerFactory);
            }

            return services;
        }
    }
}